package top.cardone.context.func;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.util.func.Func1;
import top.cardone.core.util.func.Func3;

import java.util.Map;

/**
 * @author yao hai tao
 * @date 2016/9/14
 */
public class ConversionFunc implements Func1<Object, Object>, Func3<Object, Map<String, Object>, Map<String, Object>, String> {
    @Setter
    private String converterBenaId;

    @Getter(lazy = true)
    private final Converter converter = this.converter();

    private Converter converter() {
        return ApplicationContextHolder.getBean(Converter.class, converterBenaId);
    }

    @Override
    public Object func(Object obj) {
        if (obj == null) {
            return obj;
        }

        if (obj instanceof String) {
            if (StringUtils.isBlank((String) obj)) {
                return null;
            }
        } else {
            if (StringUtils.startsWithAny(converterBenaId, "string")) {
                return obj;
            }
        }

        return this.getConverter().convert(obj);
    }

    @Override
    public Object func(Map<String, Object> map, Map<String, Object> params, String key) {
        key = MapUtils.getString(params, "key", key);

        Object val = MapUtils.getObject(map, key);

        if (val == null) {
            return this.func(MapUtils.getObject(params, "defaultValue"));
        }

        if (val instanceof String) {
            if (StringUtils.isBlank((String) val)) {
                return this.func(MapUtils.getObject(params, "defaultValue"));
            }
        }

        return this.func(val);
    }
}